package com.wshl.aijiuunion.controller.fragment;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.ViewFlipper;

import com.blankj.utilcode.util.ActivityUtils;
import com.blankj.utilcode.util.GsonUtils;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.SPUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.stx.xhb.xbanner.XBanner;
import com.wshl.aijiuunion.GlobConstant;
import com.wshl.aijiuunion.NetUrl;
import com.wshl.aijiuunion.R;
import com.wshl.aijiuunion.callback.RequestCallback;
import com.wshl.aijiuunion.controller.activity.JIamengShebeiActivity;
import com.wshl.aijiuunion.controller.activity.SearchActivity;
import com.wshl.aijiuunion.controller.activity.SelectTypeActivity;
import com.wshl.aijiuunion.controller.activity.StoreListActivity;
import com.wshl.aijiuunion.controller.activity.WebActivity;
import com.wshl.aijiuunion.model.RequestModel;
import com.wshl.aijiuunion.utils.BarUtils;
import com.wshl.aijiuunion.utils.GlideUtils;
import com.wshl.aijiuunion.utils.LocationUtil;
import com.wshl.aijiuunion.utils.share.LoginOutUtils;
import com.wshl.aijiuunion.view.adapter.FujinStoreAdapter;
import com.wshl.aijiuunion.view.adapter.GoodsAdapter;
import com.wshl.aijiuunion.view.adapter.QIanYueStoreAdapter;
import com.wshl.aijiuunion.view.bean.Bannerbean;
import com.wshl.aijiuunion.view.bean.FujinStoreBean;
import com.wshl.aijiuunion.view.bean.GoodsBean;
import com.wshl.aijiuunion.view.bean.HomeDataBean;
import com.wshl.aijiuunion.view.bean.QIanYueStoreBean;
import com.wshl.aijiuunion.view.widget.Loadingdialog;
import com.wshl.aijiuunion.view.widget.RoundCornerImageView;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;

/**
 * Created buy 风凊扬 on 2019/10/21 0021
 */
public class HomeFragment extends TabFragment implements OnRefreshListener {

    @BindView(R.id.img_msg)
    ImageView imgMsg;
    @BindView(R.id.home_xbanner)
    XBanner xbanner;
    @BindView(R.id.mFipper)
    ViewFlipper mFipper;
    @BindView(R.id.tv_jmtitle)
    TextView tvJmtitle;
    @BindView(R.id.img_jiameng)
    RoundCornerImageView imgJiameng;
    @BindView(R.id.rl_jiameng)
    RelativeLayout rlJiameng;
    @BindView(R.id.tv_mendian)
    TextView tvMendian;
    @BindView(R.id.line1)
    View line1;
    @BindView(R.id.recycle_qianyue)
    RecyclerView recycleQianyue;
    @BindView(R.id.tv_fujin)
    TextView tvFujin;
    @BindView(R.id.tv_fujin_more)
    TextView tvFujinMore;
    @BindView(R.id.line2)
    View line2;
    @BindView(R.id.recycle_fujin)
    RecyclerView recycleFujin;
    @BindView(R.id.img_left)
    RoundCornerImageView imgLeft;
    @BindView(R.id.img_righttop)
    RoundCornerImageView imgRighttop;
    @BindView(R.id.img_rightbottom)
    RoundCornerImageView imgRightbottom;
    @BindView(R.id.recycle_tuijian)
    RecyclerView recycleGoods;
    Unbinder unbinder;
    @BindView(R.id.tv_city)
    TextView tvCity;
    @BindView(R.id.rl_msg)
    RelativeLayout rlMsg;

    @BindView(R.id.tv_jiameng)
    TextView tvJiameng;
    @BindView(R.id.tv_tel)
    TextView tvTel;
    @BindView(R.id.img_show)
    ImageView imgShow;
    @BindView(R.id.refresh_home)
    SmartRefreshLayout mRefresh;
    @BindView(R.id.et_sousuo)
    EditText etSousuo;
    @BindView(R.id.img_redpoint)
    ImageView imgRedpoint;
    @BindView(R.id.tv_msg_count)
    TextView tvMsgCount;
    @BindView(R.id.ll_top)
    RelativeLayout llTop;
    private String telephone;

    @Override
    public void initImmersionBar() {
        BarUtils.setStatusBarForFragment(this);
    }

    private RequestModel requestModel;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

        LogUtils.i("homefragment--onCreateView");
        View view = inflater.inflate(R.layout.fragment_home, container, false);
        unbinder = ButterKnife.bind(this, view);
        return view;

    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        requestModel = new RequestModel();
        LocationUtil.openGPSSettings(mContext);
        LocationUtil.setOnGetLocationListener(locationlistener);
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        initView();
        initData();
        // getHomeData();
    }


    @Override
    public void onResume() {
        super.onResume();

        boolean isShould = SPUtils.getInstance().getBoolean(GlobConstant.OPENLOCATION);
        if (isShould) {
            SPUtils.getInstance().put(GlobConstant.OPENLOCATION, false);
            LocationUtil.openGPSSettings(mContext);
        }
        //  LocationUtil.openGPSSettings(mContext);
    }

    private void initView() {
        mRefresh.setOnRefreshListener(this);
        mRefresh.setEnableLoadMore(false);//禁止上拉加载更多
        //横向的recycleview,签约门店
        LinearLayoutManager layoutManager = new LinearLayoutManager(mContext);
        layoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
        recycleQianyue.setLayoutManager(layoutManager);
        //附近门店
        recycleFujin.setLayoutManager(new LinearLayoutManager(mContext));
        //推荐商品
        recycleGoods.setLayoutManager(new GridLayoutManager(mContext, 2));
        // recycleGoods.setLayoutManager(new StaggeredGridLayoutManager(2, LinearLayout.VERTICAL));
        //recycleGoods.setPadding(12, 12, 12, 12);

        recycleQianyue.setHasFixedSize(true);
        recycleQianyue.setNestedScrollingEnabled(false);
        recycleGoods.setHasFixedSize(true);
        recycleGoods.setNestedScrollingEnabled(false);
        recycleFujin.setHasFixedSize(true);
        recycleFujin.setNestedScrollingEnabled(false);
    }


    private LocationUtil.GetLocationListener locationlistener = new LocationUtil.GetLocationListener() {
        @Override
        public void getLocationInfo(double longtitude, double latitude) {

        }

        @Override
        public void getLocation(double longtitude, double latitude, String province, String city, String country) {

            LogUtils.i("定位城市:" + city + "," + country);
            if (!TextUtils.isEmpty(city) && !TextUtils.isEmpty(country)) {
                tvCity.setText(country);
                SPUtils.getInstance().put(GlobConstant.LATITUDE, latitude + "");
                SPUtils.getInstance().put(GlobConstant.LNGTITUDE, longtitude + "");
            }
            getHomeData();
        }
    };

    private void getHomeData() {

        requestModel.getHomeData(mContext, new RequestCallback() {


            @Override
            public void onSuccess(String response) {
                mRefresh.finishRefresh();

                try {
                    JSONObject jsonObject = new JSONObject(response);
                    if (jsonObject.has("code")) {
                        String code = jsonObject.getString("code");
                        switch (code) {
                            case GlobConstant.REQUESTSUCCESS:
                                HomeDataBean homeDataBean = GsonUtils.fromJson(response, HomeDataBean.class);
                                HomeDataBean.DataBean data = homeDataBean.getData();
                                if (data != null) {
                                    String kefu = data.getKefu();
                                    if (!TextUtils.isEmpty(kefu)) {
                                        telephone = kefu;
                                        SPUtils.getInstance().put(GlobConstant.KEFUTEL,kefu);
                                    }
                                    String has_msg = data.getHas_msg();
                                    if (!TextUtils.isEmpty(has_msg)) {
                                        if (has_msg.equals("0")) {

                                            imgRedpoint.setVisibility(View.GONE);
                                        } else {

                                            imgRedpoint.setVisibility(View.VISIBLE);
                                        }
                                    }


                                    List<HomeDataBean.DataBean.BannerBean> banner = data.getBanner();
                                    List<HomeDataBean.DataBean.NoticeBean> notice = data.getNotice();
                                    List<HomeDataBean.DataBean.ProductBean> product = data.getProduct();
                                    List<HomeDataBean.DataBean.StoreListBean> store_list = data.getStore_list();
                                    List<HomeDataBean.DataBean.StoreRecommendBean> store_recommend = data.getStore_recommend();

                                    if (banner != null && banner.size() > 0) {
                                        setBanner(banner);
                                    }

                                    if (notice != null && notice.size() > 0) {

                                        setNotice(notice);
                                    }

                                    if (product != null && product.size() > 0) {
                                        setProduct(product);
                                    }

                                    if (store_list != null && store_list.size() > 0) {
                                        setFujinStore(store_list);
                                    }

                                    if (store_recommend != null && store_recommend.size() > 0) {
                                        setQianyueStore(store_recommend);
                                    }

                                }
                                break;
                            case GlobConstant.REQUESTERROR://token过期失效
                                LoginOutUtils.reLogin(mContext);
                                break;
                            default:
                                if (jsonObject.has("msg")) {
                                    ToastUtils.showLong(jsonObject.getString("msg"));
                                }
                                break;
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onError(int code) {
                mRefresh.finishRefresh();
                LogUtils.e("首页数据:" + code);
            }

            @Override
            public void onIntentError() {

                mRefresh.finishRefresh();
            }
        });
    }

    private void setQianyueStore(List<HomeDataBean.DataBean.StoreRecommendBean> store_recommend) {
        qianYUeStoreBeanList = new ArrayList<>();

        for (HomeDataBean.DataBean.StoreRecommendBean storeRecommendBean : store_recommend) {
            qianYUeStoreBeanList.add(new QIanYueStoreBean(storeRecommendBean.getImages(), storeRecommendBean.getId(), storeRecommendBean.getName(), storeRecommendBean.getThumb(), storeRecommendBean.getPhone(), storeRecommendBean.getLat(), storeRecommendBean.getLng(), storeRecommendBean.getOpen_time(), storeRecommendBean.getAddress()));

        }

        qIanYueStoreAdapter = new QIanYueStoreAdapter(recycleQianyue);
        qIanYueStoreAdapter.setData(qianYUeStoreBeanList);
        recycleQianyue.setAdapter(qIanYueStoreAdapter);
    }

    private void setFujinStore(List<HomeDataBean.DataBean.StoreListBean> store_list) {
        fujinStoreBeanList = new ArrayList<>();
        for (HomeDataBean.DataBean.StoreListBean storeListBean : store_list) {
            fujinStoreBeanList.add(new FujinStoreBean((ArrayList<String>) storeListBean.getImages(), storeListBean.getAddress(), storeListBean.getDistance(), storeListBean.getId(), storeListBean.getName(), storeListBean.getPhone(), storeListBean.getThumb(), storeListBean.getLat(), storeListBean.getLng(), storeListBean.getOpen_time()));

        }
        fujinStoreAdapter = new FujinStoreAdapter(recycleFujin);
        fujinStoreAdapter.setData(fujinStoreBeanList);
        recycleFujin.setAdapter(fujinStoreAdapter);
    }

    private void setProduct(List<HomeDataBean.DataBean.ProductBean> product) {
        goodsBeanList = new ArrayList<>();
        for (HomeDataBean.DataBean.ProductBean productBean : product) {
            goodsBeanList.add(new GoodsBean(productBean.getCover(), productBean.getId(), productBean.getOld_price(), productBean.getPrice(), productBean.getSales(), productBean.getSku(), productBean.getTitle()));
        }
        goodsAdapter = new GoodsAdapter(recycleGoods);
        goodsAdapter.setData(goodsBeanList);
        recycleGoods.setAdapter(goodsAdapter);
    }

    private void setNotice(List<HomeDataBean.DataBean.NoticeBean> notice) {
        if (mFipper.isFlipping()) {
            mFipper.stopFlipping();
        }
        if (mFipper.getChildCount() > 0) {
            mFipper.removeAllViews();//先清除之前的条目,然后再添加新的内容
        }

        for (HomeDataBean.DataBean.NoticeBean noticeBean : notice) {
            View view = LayoutInflater.from(mContext).inflate(R.layout.item_fipper, null);
            TextView tvfipper = view.findViewById(R.id.tv_fipper_item_content);
            tvfipper.setText(noticeBean.getTitle());
            mFipper.addView(view);
        }

        mFipper.startFlipping();
    }


    private void setBanner(final List<HomeDataBean.DataBean.BannerBean> bannerdata) {

        final List<String> imageUrls = new ArrayList<>();
        List<Bannerbean> banners = new ArrayList<>();
        for (HomeDataBean.DataBean.BannerBean bannerdatum : bannerdata) {
            banners.add(new Bannerbean(NetUrl.IMG + bannerdatum.getCover()));
            imageUrls.add(NetUrl.IMG + bannerdatum.getCover());
        }

        xbanner.setBannerData(banners);
        xbanner.loadImage(new XBanner.XBannerAdapter() {
            @Override
            public void loadBanner(XBanner banner, Object model, View view, int position) {
                GlideUtils.loadImage(mContext, ((Bannerbean) model).getXBannerUrl(), (ImageView) view);

            }
        });
        xbanner.setOnItemClickListener(new XBanner.OnItemClickListener() {
            @Override
            public void onItemClick(XBanner banner, Object model, View view, int position) {

                Intent intent = new Intent(mContext, WebActivity.class);
                intent.putExtra(GlobConstant.WEBURL, bannerdata.get(position).getLinkurl());
                startActivity(intent);
            }
        });
    }

    private List<GoodsBean> goodsBeanList;
    private List<FujinStoreBean> fujinStoreBeanList;
    private List<QIanYueStoreBean> qianYUeStoreBeanList;

    private GoodsAdapter goodsAdapter;
    private FujinStoreAdapter fujinStoreAdapter;
    private QIanYueStoreAdapter qIanYueStoreAdapter;

    private void initData() {
        //热点播报
        mFipper.setInAnimation(mContext, R.anim.in_bottomtop);
        mFipper.setOutAnimation(mContext, R.anim.out_bottomtop);


    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (!hidden) {

        } else {

            Loadingdialog.dismiss();
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
        Loadingdialog.dismiss();
    }

    @OnClick({R.id.et_sousuo, R.id.mFipper, R.id.tv_jiameng, R.id.tv_tel, R.id.img_show, R.id.tv_city, R.id.rl_msg, R.id.rl_jiameng, R.id.tv_fujin_more})
    public void onViewClicked(View view) {
        String token = SPUtils.getInstance().getString(GlobConstant.TOKEN);

        switch (view.getId()) {

            case R.id.et_sousuo:
                if (TextUtils.isEmpty(token)) {
                    LoginOutUtils.reLogin(mContext);
                    return;
                }
                ActivityUtils.startActivity(SearchActivity.class);
                break;
            case R.id.mFipper:
                if (TextUtils.isEmpty(token)) {
                    LoginOutUtils.reLogin(mContext);
                    return;
                }
                startMsg(token, NetUrl.NEWS);
                break;
            case R.id.tv_jiameng:

                String type = SPUtils.getInstance().getString(GlobConstant.TYPE, "4");
                if (TextUtils.equals("1", type)) {
                    ToastUtils.showLong("当前身份已是最高级别");
                    return;
                }
                ActivityUtils.startActivity(SelectTypeActivity.class);
                break;
            case R.id.tv_tel:

                if (!TextUtils.isEmpty(telephone)) {
                    Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + telephone));
                    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    startActivity(intent);
                }

                break;
            case R.id.img_show:

                imgShow.setSelected(!imgShow.isSelected());
                if (imgShow.isSelected()) {
                    tvTel.setVisibility(View.VISIBLE);
                } else {
                    tvTel.setVisibility(View.GONE);
                }
                break;
            case R.id.tv_city:
                LocationUtil.openGPSSettings(mContext);
                LocationUtil.setOnGetLocationListener(locationlistener);
                //ActivityUtils.startActivity(mContext, LocationActivity.class);
                break;
            case R.id.rl_jiameng://加盟招商政策

                startMsg(token, NetUrl.NEWSDETAILS);
                break;
            case R.id.tv_fujin_more://附近的店
                ActivityUtils.startActivity(StoreListActivity.class);
                break;

            case R.id.rl_msg:
                if (TextUtils.isEmpty(token)) {
                    LoginOutUtils.reLogin(mContext);
                    return;
                }
                imgRedpoint.setVisibility(View.GONE);
                startMsg(token, NetUrl.NEWS);

                break;
        }
    }

    private void startMsg(String token, String url) {

        Intent intent2 = new Intent(mContext, WebActivity.class);
        intent2.putExtra(GlobConstant.WEBURL, url + token);
        ActivityUtils.startActivity(intent2);
    }

    private void startWeb(String token, String keyword) {

        Intent intent = new Intent(mContext, WebActivity.class);
        intent.putExtra(GlobConstant.WEBURL, NetUrl.GOODSLIST + token + "&type=" + keyword);
        ActivityUtils.startActivity(intent);
    }


    @Override
    public void onRefresh(@NonNull RefreshLayout refreshLayout) {
        LocationUtil.openGPSSettings(mContext);
        LocationUtil.setOnGetLocationListener(locationlistener);
    }

    @OnClick(R.id.img_left)
    public void onImgLeftClicked() {
        String token = SPUtils.getInstance().getString(GlobConstant.TOKEN);
        startWeb(token, "1");
    }

    @OnClick(R.id.img_righttop)
    public void onImgRighttopClicked() {
        String token = SPUtils.getInstance().getString(GlobConstant.TOKEN);
        startWeb(token, "2");
    }

    @OnClick(R.id.img_rightbottom)
    public void onImgRightbottomClicked() {
        String token = SPUtils.getInstance().getString(GlobConstant.TOKEN);
        startWeb(token, "3");
    }
}
